package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.dto.yx7881.utils.HttpUtil;
import com.ruoyi.system.outto.goods.TaoShouYouAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TaoShouYouApiImpl implements TaoShouYouAPI {

    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    InterAttrMapper interAttrMapper;

    static String sign;
    static String timestamp;

    public static void main(String[] args) {
        String string = getAttr("王者荣耀");
        System.out.println(string);
    }

    static String addGames(){
        String url = "https://www.taoshouyou.com/api/trades-union/publish";
        Map<String,Object> params = new TreeMap<>();
        Map<String,Object> data = new TreeMap<>();
        Map<String,Object> header = new HashMap<>();
        params.put("acc","171075474");
        params.put("clientId","30");
        params.put("code","ry_17541");
        params.put("gameId","2256");
        params.put("insuranceType","0");
        params.put("price","220.0");
        params.put("productName","王者荣耀");
        params.put("pwd","123456");
        params.put("mobile","12345678911");
        params.put("serviceAreaId","1083233");
        params.put("picHost","https://game.ikbh.top");
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);
        String salt = "e0u6fnlag0";
        String cover1 = getCover(params);
        String cover = salt+timestamp+cover1+"122596784f00da10328dd13719a6a2c45fafd4f7";
        System.out.println(cover);
        String sign = DigestUtils.sha256Hex(cover);
        sign = salt+sign;
        List<Object> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("id","9030");
        map.put("value","无");
        list.add(map);
        map = new HashMap<>();
        map.put("id","8704");
        map.put("value","0");
        list.add(map);
        map = new HashMap<>();
        map.put("id","8703");
        map.put("value","0");
        list.add(map);
        map = new HashMap<>();
        map.put("id","16227");
        map.put("value","倔强青铜");
        list.add(map);
        map = new HashMap<>();
        map.put("id","8690");
        map.put("value","无");
        list.add(map);
        map = new HashMap<>();
        map.put("id","8690");
        map.put("value","无");
        list.add(map);
        params.put("attr",list);
        data.put("data", JSONObject.toJSONString(params));
        System.out.println(sign);
        header.put("AppId","12259678");
        header.put("AppKey","4f00da10328dd13719a6a2c45fafd4f7");
        header.put("timestamp",timestamp);
        header.put("sign",sign);
        String string = HttpUtils.doPostFormData(url,data, header);
        System.out.println(MapUntils.unicodeToString(string));
        return string;
    }

    static String getGames(){
        String body = HttpRequest.get("https://www.taoshouyou.com/com/game/gamelist-interface").execute().body();
        return MapUntils.unicodeToString(body);
    }

    static String getArea(String gameName){
        String url = "https://www.taoshouyou.com/api/trades-union/getarea";
        Map<String,Object> params = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        Map<String,Object> header = new HashMap<>();
        params.put("name",gameName);
        data.put("data",JSONObject.toJSONString(params));
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);
        System.out.println(timestamp);
        String salt = "e0u6fnlag0";
        String cover1 = getCover(data);
        cover1 = cover1.substring(0,cover1.length()-1);
        String cover = salt+timestamp+cover1+"122596784f00da10328dd13719a6a2c45fafd4f7";
        System.out.println(cover);
        String sign = DigestUtils.sha256Hex(cover);
        System.out.println(sign);
        header.put("AppId","12259678");
        header.put("AppKey","4f00da10328dd13719a6a2c45fafd4f7");
        header.put("timestamp",timestamp);
        header.put("sign","salt"+sign);
        String string = HttpUtils.doPostFormData(url, data, header);
        return string;
    }
    static String getAttr(String gameName){
        String url = "https://www.taoshouyou.com/api/trades-union/getattr";
        Map<String,Object> params = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        Map<String,Object> header = new HashMap<>();
        params.put("name",gameName);
        data.put("data",JSONObject.toJSONString(params));
        String timestamp = String.valueOf(System.currentTimeMillis()/1000);
        System.out.println(timestamp);
        String salt = "e0u6fnlag0";
        String cover1 = MapUntils.getCover(data);
        cover1 = cover1.substring(0,cover1.length()-1);
        String cover = salt+timestamp+cover1+"122596784f00da10328dd13719a6a2c45fafd4f7";
        System.out.println(cover);
        String sign = DigestUtils.sha256Hex(cover);
        System.out.println(sign);
        header.put("AppId","12259678");
        header.put("AppKey","4f00da10328dd13719a6a2c45fafd4f7");
        header.put("timestamp",timestamp);
        header.put("sign",sign);
        String string = HttpUtils.doPostFormData(url, data, header);
        System.out.println(MapUntils.unicodeToString(string));
        return string;
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa, String type) {
        Map<String,Object> params = new TreeMap<>();
        Map<String,Object> data = new TreeMap<>();
        if(type.equals("update")) {
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(sa.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            ArtRec artRec = artRecs.get(0);
            params.put("productCode", artRec.getOutid());
        }
        params.put("acc", goodsInfoAndAttrValueDto.getAccountNumber());
        params.put("code", String.valueOf(System.currentTimeMillis()).substring(5));
        params.put("price", new BigDecimal(Math.ceil(goodsInfoAndAttrValueDto.getPrice().doubleValue())));
        params.put("mobile", sa.getThreeOther());//联系电话
        params.put("picHost", sa.getTwoOther());
        params.put("pwd", "123456");
        params.put("insuranceType", "0");
        params.put("picHost", sa.getTwoOther());//接入方平台图片服务器地址
        params.put("productName", goodsInfoAndAttrValueDto.getTitle());

        //属性匹配
        String substring = sa.getSaleName().substring(sa.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        params.put("gameId",interAttr.getInterGameId().split("-")[0]);
        //区服匹配
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());
        if(goodsInfoAndAttrValueDto.getGameName().equals("三角洲行动")){
            params.put("clientId", "46");
            params.put("serviceAreaId", "11293991");
        }

        String salt = "e0u6fnlag0";
        timestamp = String.valueOf(System.currentTimeMillis()/1000);
        System.out.println(JSONObject.toJSONString(params));
        String cover1 = getCover(params);
        System.out.println(cover1);
        String cover = salt+timestamp+cover1+sa.getSaleKey()+sa.getOther();
        System.out.println(cover);
        sign = DigestUtils.sha256Hex(cover);
        sign = salt+sign;


        List list = new ArrayList();
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, interAttr.getRadioAttr(),list);
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, interAttr.getCheckAttr(),list);
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, interAttr.getInputAttr(),list);

        if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")){
            Map<String,Object> map = new HashMap<>();
            map.put("id","16422");
            map.put("value", "网易账号");
            list.add(map);
        }

        params.put("attr",list);
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgurl = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining(","));
        params.put("picList",imgurl.split(","));
        data.put("data",JSONObject.toJSONString(params));
        return data;
    }


    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String inputAttr, List<Object> list) {
//        JSONArray propertys = Objects.isNull(params.get("property")) ? new JSONArray() : JSONArray.parseArray(params.get("property").toString());
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        Map<String,Object> map = new HashMap<>();
        for (JSONObject object : jsonObjects1) {
            map = new HashMap<>();
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            Object o = null;
                            try {
                                o = declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            String oneValue = String.valueOf(o);
                            if (StringUtils.isNotEmpty(oneValue)) {
                                map.put("id", interId);
                                map.put("value", oneValue);
                            }
                        }
                    }
                }
            }
            if(Objects.nonNull(map.get("value"))){
                list.add(map);
            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            map = new HashMap<>();
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                if(object.getString("name").equals("账号亮点")){
                    map.put("id", defaultValue);
                    map.put("value", goodsInfoAndAttrValueDto.getDes());
                }else if(object.getString("name").equals("VIP等级")){
                    if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")) {
                        map.put("id", defaultValue);
                        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
                            GameAttribute gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
                            map.put("value", gameAttribute.getFieldName().replace("V",""));
                        }
                    }
                }else {
                    map.put("id", defaultValue);
                    map.put("value", "0");
                }
            }
            if(Objects.nonNull(map.get("value"))){
                list.add(map);
            }
        }

    }
    /**
     * 开始匹配单选属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param radioAttr
     */
    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String radioAttr, List<Object> list) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (!org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            /**
             * 1、先查询自定义中所有单选的字段
             * 2、再查该账号单选字段中的选项
             * 3、再去接口属性匹配表过滤
             */
            GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
            gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
            gameAttrTemplate.setIsEnable("0");
            gameAttrTemplate.setFieldType("radio");
            List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
            Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


            List<JSONObject> defObjects = new ArrayList<>();
            defObjects.addAll(jsonObjects);


            //属性 不参与加密
            Map<String,Object> map = new HashMap<>();

            for (JSONObject object : jsonObjects) {
                map = new HashMap<>();
                for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                    String aavName = attrTemplate.getAavName();
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (aavName.equals(name)) {
                            //一级属性
                            //注意 YdConfigId 对应的是 f字段对应的 id
                            if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                                String InterConfigId = object.getString("InterConfigId");
                                defObjects.remove(object);//如果匹配上，则去掉
                                String interRadioReqs1 = object.getString("interRadioReqs");
                                List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                                declaredField.setAccessible(true);
                                try {
                                    //获取选择的值 例如  实名中的可二次
                                    Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                    String oneValue = String.valueOf(o);
                                    List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId"))?j.getString("YdConfigId").contains(oneValue):"111".contains(oneValue)).collect(Collectors.toList());
                                    String interConfigName = object.getString("InterConfigName");
                                    String defaultValue = object.getString("defaultValue");
                                    if (org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        if (StringUtils.isNotEmpty(defaultValue)) {
                                            map.put(InterConfigId, defaultValue);
                                        }
                                    }
                                    if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        JSONObject jsonObject2 = twoAttr.get(0);
                                        String interConfigId2 = jsonObject2.getString("InterConfigId");
                                        map.put("id", InterConfigId);
                                        map.put("value", interConfigId2);
                                        if(Objects.nonNull(map.get("value"))){
                                            list.add(map);
                                        }
                                    }
                                } catch (Exception e) {
                                    throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                            }
                        }
                    }
                }
            }
            //开始匹配默认值
            for (JSONObject object : defObjects) {
                map = new HashMap<>();
                String id = object.getString("id");
                if(StringUtils.isNotEmpty(object.getString("defaultValue"))){
                    map.put("id", id);
                    map.put("value", object.getString("defaultValue"));
                }else {
                    interRadioReqs = object.getString("interRadioReqs");
                    jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
                    for (JSONObject objects : jsonObjects) {
                        if (StringUtils.isNotEmpty(objects.getString("defaultValue"))) {
                            map.put("id", id);
                            map.put("value", objects.getString("defaultValue"));
                        }
                    }
                }
                if (Objects.nonNull(map.get("value"))) {
                    list.add(map);
                }
            }
            //========================单选属性匹配结束=====================//
        }
    }
    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String checkAttr, List<Object> list) {
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Map<String,Object> map = new HashMap<>();
        for (JSONObject object : checkJsonList) {
            map = new HashMap<>();
            String string = "";
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);
                        Object o = null;
                        try {
                            o = declaredField.get(goodsInfoAndAttrValueDto);
                        } catch (IllegalAccessException e) {
                            throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                        }
                        String oneValue = String.valueOf(o);
                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
                        //开始匹配二级属性
                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                        /**
                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                         */
                        for (JSONObject jsonObject1 : jsonObjects2) {
                            String[] split1 = oneValue.split(",");
                            String ydConfigId1 = jsonObject1.getString("YdConfigId");
                            if(StringUtils.isNotEmpty(ydConfigId1)) {
                                ydConfigId1 = ydConfigId1.replace(" ", "");
                                for (String s : split1) {
                                    if (Objects.equals(s, ydConfigId1)) {
                                        String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                        string+=","+InterConfigId2;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            map.put("id", object.getString("id"));
            if(StringUtils.isNotEmpty(string)){
                map.put("value", string.substring(1));
            }else {
                map.put("value", "无");
            }
            list.add(map);
        }
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {

        JSONObject serjsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = serjsonObject.getString("interServeReqs");
        List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            String qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (Objects.equals(ydServeId, qufuid)) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("clientId", object.getString("id"));
                        params.put("serviceAreaId", twoServer.get(0).getString("id"));
                        break;
                    }
                }
            }
        }else if (Objects.equals(goodsInfoAndAttrValueDto.getGameName(), "永劫无间")) {
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (ydServeId.contains(goodsInfoAndAttrValueDto.getGroupId().toString())) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("clientId", object.getString("id"));
                        params.put("serviceAreaId", twoServer.get(0).getString("id"));
                        break;
                    }
                }
            }
        }else {
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (ydServeId.contains(goodsInfoAndAttrValueDto.getGroupId().toString())) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("clientId", object.getString("id"));
                        for (JSONObject object2 : twoServer) {
                            String ydServeId2 = object2.getString("YdServeId");
                            ydServeId2 = ydServeId2.replace(",", "").replace(" ", "");
                            if (ydServeId2.contains(goodsInfoAndAttrValueDto.getServerId().toString())) {
                                params.put("serviceAreaId", object2.getString("id"));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String url = "https://www.taoshouyou.com/api/trades-union/publish";
        Map<String, Object> resultMap = new HashMap<>();
        Map<String,Object> header = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner,"add");
        log.info("淘手游添加接口请求参数={}", JSONObject.toJSONString(params));
        header.put("AppId",salePartner.getSaleKey());
        header.put("AppKey",salePartner.getOther());
        header.put("timestamp",timestamp);
        header.put("sign",sign);
        String string = HttpUtils.doPostFormData(url, params, header);
        JSONObject resultJson = JSONObject.parseObject(string);
        log.info("淘手游添加接口返回参数={}", resultJson);
        if (!"200".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            String data = resultJson.getString("data");
            String productCode = JSONObject.parseObject(data).getString("productCode");
            resultMap.put("outId", productCode);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", resultJson);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String url = "https://www.taoshouyou.com/api/trades-union/publish";
        Map<String, Object> resultMap = new HashMap<>();
        Map<String,Object> header = new HashMap<>();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, salePartner,"update");
        log.info("淘手游编辑接口请求参数={}", JSONObject.toJSONString(params));
        header.put("AppId",salePartner.getSaleKey());
        header.put("AppKey",salePartner.getOther());
        header.put("timestamp",timestamp);
        header.put("sign",sign);
        String string = HttpUtils.doPostFormData(url, params, header);
        JSONObject resultJson = JSONObject.parseObject(string);
        log.info("淘手游编辑接口返回参数={}", resultJson);
        if (!"200".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", resultJson);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        String url = "https://www.taoshouyou.com/api/trades-union/synch";
        Map<String, Object> resultMap = new HashMap<>();
        Map<String,Object> header = new HashMap<>();
        Map<String, Object> params = new TreeMap<>();
        Map<String, Object> data = new TreeMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        params.put("productCode",artRec.getOutid());
        params.put("state",2);
        String salt = "e0u6fnlag0";
        timestamp = String.valueOf(System.currentTimeMillis()/1000);
        System.out.println(JSONObject.toJSONString(params));
        String cover1 = getCover(params);
        System.out.println(cover1);
        String cover = salt+timestamp+cover1+salePartner.getSaleKey()+salePartner.getOther();
        System.out.println(cover);
        sign = DigestUtils.sha256Hex(cover);
        sign = salt+sign;
        data.put("data",JSONObject.toJSONString(params));
        log.info("淘手游删除接口请求参数={}", JSONObject.toJSONString(params));
        header.put("AppId",salePartner.getSaleKey());
        header.put("AppKey",salePartner.getOther());
        header.put("timestamp",timestamp);
        header.put("sign",sign);
        String string = HttpUtils.doPostFormData(url, data, header);
        JSONObject resultJson = JSONObject.parseObject(string);
        log.info("淘手游删除接口返回参数={}", resultJson);
        if (!"200".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", resultJson);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }
    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    public static String offGoods(String tradeid, SalePartner salePartner){
        String attrUrl = "https://www.taoshouyou.com/user/sellertrade/putoffsale";
        Map<String,String> params = new HashMap<>();
        params.put("tradeid",tradeid);
        params.put("reason","%E4%B8%8D%E6%83%B3%E5%8D%96%E4%BA%86");

        Map<String,String> header = new HashMap<>();
        String s = HttpUtil.doGet(attrUrl, params, header);
        log.info("淘手游下架接口请求参数={}", JSONObject.toJSONString(params));
        log.info("淘手游下架接口返回参数={}", MapUntils.unicodeToString(s));
        return s;
    }

    public static String getCover(Map<String,Object> params){


        log.info("通过Map.keySet遍历key和value：");

        StringBuffer resut = new StringBuffer();

        for (String key : params.keySet()) {

            log.info("key= "+ key + " and value= " + params.get(key));

            if (Objects.nonNull(params.get(key)) && StringUtils.isNotEmpty(String.valueOf(params.get(key)))){
                resut.append(params.get(key));
            }

        }
        return resut.toString();
    }

    //只保留中文
    private String onlyHanZi(String str) {
        String reg = "[^\u4e00-\u9fa5]";
        str = str.replaceAll(reg, "");
        return str;
    }
}
